package com.xhy.documents_collection.controller;

import com.xhy.documents_collection.entity.PO.User;
import com.xhy.documents_collection.service.UserService;
import com.xhy.documents_collection.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: Xhy
 * CreateTime: 2022-11-16 14:23
 */
@Controller
public class IndexController {



    private String url;

    @Value("${url}")
    public void setUrl(String url) {
        this.url = url+":";
    }

    @RequestMapping("/")
    public void loginPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendRedirect(url+request.getServerPort()+"/page/login.html");
    }

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping("/temp")
    public R userTemp(){
        Map<String, String> map = new HashMap<>();
        map.put("email","123@qq.com");
        map.put("userName","张三");
        map.put("studentNumber","123456");
        return R.ok().data("data",map);
    }

    @ResponseBody
    @PostMapping("/user/update")
    public R updateUser(@RequestBody User user,HttpServletRequest request){

        user.setId(Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request)));
        return userService.updateUser(user);
    }

    @GetMapping("/user/get")
    @ResponseBody
    public R getUser(HttpServletRequest request){
        String uId = JwtUtils.getMemberIdByJwtToken(request);
        return R.ok().data("data",userService.getById(uId));
    }

    @PostMapping("/parseTemp")
    @ResponseBody
    public R parseTemp(String template,HttpServletRequest request){

        if (!Template.verify(template)){
            return R.error().message("模板不合规");
        }
        String uId = JwtUtils.getMemberIdByJwtToken(request);
        if (ObjectUtils.isEmpty(uId)){
            return R.error().message("请登录以后再访问");
        }
        User user = userService.getById(uId);
        String parseTemp = null;
        try {
            parseTemp = Template.parseTemp(template, user);
        } catch (Exception e) {
            return R.error().message("没有这样的字段");
        }
        return R.ok().message(parseTemp);
    }



}
